﻿using CloudStorageLight.Core;
using CloudStorageLight.Core.Web;
using CloudStorageLight.SharePointWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;

namespace CloudStorageLight.SharePointWeb.Controllers
{
    public class WebPartController : FilesControllerBase
    {
        protected override BlobService CreateBlobService()
        {
            //BasicAuthenticateUtil.Init();
            return new BlobService();
        }


        protected override BlobUser GetCurrentUser()
        {
            if (_user == null)
            {
                if (!HttpContext.User.Identity.IsAuthenticated) TrySpLogin();
                if (!this.HttpContext.User.Identity.IsAuthenticated) throw new BlobException(BlobExceptionCode.NotAuthorization);
                _user = BasicAuthenticateUtil.GetCurrentUser();
            }
            return _user;
        }
        private BlobUser _user;

        [SharePointContextFilter]
        public override async Task<ActionResult> Index(string id = "", string snapshot = "current", string mode = null, string baseVersion = null, string passcode = null, FormCollection fc=null)
        {
            //後ろ空白トリム対策
            var rootPath = Url.RouteUrl("webparts", new { id = "" });
            if (this.Request.Url.AbsolutePath.Length > rootPath.Length + 1)
            {
                id = BlobUtil.UnescapeDataString(this.Request.Url.AbsolutePath.Substring(rootPath.Length + 1));
            }

            this.HttpContext.Items["WebParts"] = true;
            mode = mode ?? "attachment";
            if (SystemSettings.Instance.MultiDomain)
            {
                var queryString = new RouteValueDictionary();
                foreach (var item in this.Request.QueryString.AllKeys)
                {
                    queryString.Add(item ?? "", this.Request[item]);
                }
                var domain = BlobService.GetCurrentDomain();
                if (string.IsNullOrEmpty(domain))
                {
                    var cloudAcccout = CloudAccount.LoadBySpHostUrl(SystemSettings.Instance.BlobStorage, SharePointContext.GetSPHostUrl(this.Request).AbsoluteUri);
                    if (cloudAcccout == null) throw new BlobException(BlobExceptionCode.NotAuthorization);
                    queryString.Add("domain", cloudAcccout.AccountName);
                    if (queryString.ContainsKey("initPath")) 
                    {
                        var initPath = (string)queryString["initPath"];
                        initPath = "/" + initPath.Trim('/') + "/";
                        queryString.Add("id", initPath);
                    }
                    return RedirectToAction("Index", "WebPart", queryString);
                }
            }
            return await base.Index(id, snapshot, mode, baseVersion, passcode, fc);
        }

        protected override async Task<ActionResult> Directory(BlobUser user , BlobService svc, string id)
        {
            var exist = await svc.ExistsAsync(id);
            if (!exist) throw new BlobException(BlobExceptionCode.InvalidDirectoryPath);
            var vm = await CreateFilesVM(id, user, svc);
            ViewData["files"] = await vm.Folder.GetChildren();
            Response.AddHeader("p3p", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");
            return View(vm);
        }

        private bool TrySpLogin()
        {
            try
            {
                CloudAccount cloudAcccout = CloudAccount.LoadBySpHostUrl(SystemSettings.Instance.BlobStorage, SharePointContext.GetSPHostUrl(this.Request).AbsoluteUri);
                var user = BasicAuthenticateUtil.GetCurrentUser(cloudAcccout);
                return true;
            }
            catch (BlobException ex)
            {
                if (ex.Code == BlobExceptionCode.NotAuthorization) return false;
                throw;
            }
        }

    }
}
